package com.sy.core.website;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sy.core.model.*;
import com.sy.core.util.RestResult;
import com.sy.core.web.BaseCtl;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocumentList;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 通用页面跳转
 */
@Controller
@RequestMapping("website")
public class HomeCtl extends BaseCtl{


    protected  static String prefix = "/website/";

    /**
     * 通用的跳转页面
     */
    @RequestMapping("{path}")
    public ModelAndView index(ModelAndView mv, @PathVariable String path){
        mv.setViewName(prefix+path);
        return mv;
    }

    /**
     * 首页显示
     */
    @RequestMapping("home")
    public ModelAndView homeIndex(ModelAndView mv, SyProduct syProduct){
        SysUser sysUser = getLoginUser();
        if(sysUser!=null){
            mv.addObject("user",sysUser);
        }
        //主页左侧一级分类数据
        Map<String,Object> map = new HashMap<>();
        map.put("productTypeParent","0");
        List<Map<String, Object>> productTypeList = productTypeService.queryList(map);
        mv.addObject("productTypeList",productTypeList);
        //主页右侧轮播图
        List<Map<String, Object>> banneerList = bannerService.queryList(null);
        mv.addObject("bannerList",banneerList);
        //精品商品
        syProduct.setNo2("0");
        syProduct.setNo3("1");
        List<Map<String, Object>> boutiqueProductList = productService.queyList(syProduct);
        mv.addObject("boutiqueProductList",boutiqueProductList);
        //超值推荐
        syProduct.setNo3("2");
        List<Map<String, Object>> greatValueProductList = productService.queyList(syProduct);
        mv.addObject("greatValueProductList",greatValueProductList);
        //热卖商品
        syProduct.setNo3("3");
        List<Map<String, Object>> saleHotProductList = productService.queyList(syProduct);
        mv.addObject("saleHotProductList",saleHotProductList);
        //新品上架
        syProduct.setNo3("4");
        List<Map<String, Object>> newProductList = productService.queyList(syProduct);
        mv.addObject("newProductList",newProductList);
        mv.setViewName(prefix+"home");
        return mv;
    }

    /**
     * 首页二级分类显示
     */
    @RequestMapping("secondProductType")
    @ResponseBody
    public RestResult secondProductType(String productTypeParent){
        RestResult rr = null;
        Map<String,Object> map = new HashMap<>();
        map.put("productTypeParent",productTypeParent);
        try {
            List<Map<String, Object>> productTypeList = productTypeService.queryList(map);
            rr=new RestResult("200","获取二级分类数据成功",productTypeList);
        } catch (Exception e) {
            logger.error("获取二级分类数据成功");
            rr=new RestResult("200","获取二级分类数据成功");
        }
        return rr;
    }

    /**
     * 产品列表页显示
     * @param mv
     * @return
     */
    @RequestMapping("productList")
    public String productList(ModelMap mv,SyProduct syProduct,Integer page,Integer limit){
        SysUser sysUser = getLoginUser();
        if(sysUser!=null){
            mv.addAttribute("user",sysUser);
        }
        Map<String,Object> map = new HashMap<>();
        //查询一级分类
        map.put("productTypeParent","0");
        List<Map<String, Object>> FirstProductTypeList = productTypeService.queryList(map);
        mv.addAttribute("firstProductTypeList",FirstProductTypeList);
        //查询二级列表
        List list = new ArrayList();
        for (int i = 0; i <FirstProductTypeList.size() ; i++) {
            map.put("productTypeParent",FirstProductTypeList.get(i).get("pk"));
            List<Map<String, Object>> secondProductTypeList = productTypeService.queryList(map);
            list.add(secondProductTypeList);
        }
        mv.addAttribute("list",list);
        //产品列表
        PageHelper.startPage(page,limit);
        List<Map<String, Object>> productList = productService.queyList(syProduct);
        PageInfo<Map<String,Object>> info = new PageInfo<>(productList);
        mv.addAttribute("productList",info);
        //选中的分类
        mv.addAttribute("firstPk",syProduct.getProductTypeFirst());
        mv.addAttribute("secondPk",syProduct.getProductTypeSecond());
        mv.addAttribute("no3",syProduct.getNo3());
        mv.addAttribute("currentPage",page);
        return prefix+"product_list";
    }

    /**
     * 产品详情页显示
     */
    @RequestMapping("productDetails")
    public String priductDetails(ModelMap mv,SyProductAttribute syProductAttribute,SyProductAttributeValue syProductAttributeValue){
        SysUser sysUser = getLoginUser();
        if(sysUser!=null){
            mv.addAttribute("user",sysUser);
        }
        //获取产品信息
        Map<String, Object> product = productService.queryOne(syProductAttribute.getProductPk());
        mv.addAttribute("product",product);
        //获取产品属性名称
        List<Map<String, Object>> productAttrNameList = productAttributeService.queryList(syProductAttribute);
        mv.addAttribute("productAttrNameList",productAttrNameList);
        //获取产品属性值
        List list = new ArrayList();
        for (int i = 0; i <productAttrNameList.size(); i++) {
            syProductAttributeValue.setAttrPk((String)productAttrNameList.get(i).get("pk"));
            List<Map<String, Object>> productAttrValueList = productAttributeValueService.queryList(syProductAttributeValue);
            list.add(productAttrValueList);
        }
        mv.addAttribute("list",list);
        //获取推荐商品信息
        SyProduct syProduct = new SyProduct();
        syProduct.setNo2("0");
        PageHelper.startPage(1,8);
        List<Map<String, Object>> productList = productService.queyList(syProduct);
        PageInfo<Map<String,Object>> info = new PageInfo<>(productList);
        mv.addAttribute("productList",info);
        return prefix+"product_details";
    }

    /**
     * 查询sku信息
     */
    @RequestMapping("skuList")
    @ResponseBody
    public RestResult skuList(SyProductSku syProductSku){
        RestResult rr = null;
        try {
            List<Map<String, Object>> skuList = productSkuService.queryList(syProductSku);
            rr = new RestResult("200","获取sku列表成功",skuList);
        } catch (Exception e) {
            logger.error("获取sku列表失败");
            rr = new RestResult("500","获取sku列表失败");
        }
        return rr;
    }

    /**
     * 搜索功能
     */
    @RequestMapping("product_search")
    public String  product_search(ModelMap mv,String condition,Integer page,Integer limit){
        SysUser sysUser = getLoginUser();
        if(sysUser!=null){
            mv.addAttribute("user",sysUser);
        }
        try {
            SolrQuery params = new SolrQuery();

            //查询条件, 这里的 q 对应 下面图片标红的地方
            params.set("q", condition);

            //过滤条件
            //params.set("fq", "product_price:[100 TO 100000]");

            //排序
            //params.addSort("product_price", SolrQuery.ORDER.asc);

            //分页
            params.setStart(page);
            params.setRows(limit);

            //默认域
            params.set("df", "item_keywords");

            //只查询指定域
            //params.set("fl", "item_keywords");

            //高亮
            //打开开关
            params.setHighlight(true);
            //指定高亮域
            params.addHighlightField("item_name,item_title");
            //设置前缀
            params.setHighlightSimplePre("<span style='color:red'>");
            //设置后缀
            params.setHighlightSimplePost("</span>");

            QueryResponse queryResponse = solrClient.query("shinyoukeji",params);

            SolrDocumentList results = queryResponse.getResults();

            long numFound = results.getNumFound();
            //logger.info("总数："+String.valueOf(numFound));

            //获取高亮显示的结果, 高亮显示的结果和查询结果是分开放的
            Map<String, Map<String, List<String>>> highlight = queryResponse.getHighlighting();

            for (int i = 0; i < results.size(); i++) {
                Map<String, List<String>> map = highlight.get(results.get(i).get("id"));
                List<String> list1 = map.get("item_name");
                List<String> list2 = map.get("item_title");
                if(list1!=null&&list1.size()>0){
                    results.get(i).put("item_name",list1.get(0));
                }
                if(list2!=null&&list2.size()>0){
                    results.get(i).put("item_title",list2.get(0));
                }
            }
            mv.addAttribute("productList",results);
            mv.addAttribute("condition",condition);
            mv.addAttribute("totalPage",numFound);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return prefix+"product_search";
    }

    /**
     * 头部购物车物品数量
     */
    @RequestMapping("shoppingCartCount")
    @ResponseBody
    public RestResult shoppingCartCount(SyShoppingCart syShoppingCart){
        RestResult rr = null;
        SysUser sysUser = getLoginUser();
        if(sysUser!=null){
            syShoppingCart.setShoppingCartUserpk(sysUser.getPk());
            Integer counts = shoppingCartService.queryCount(syShoppingCart);
            rr = new RestResult("200","获取购物车商品数量成功",counts);
        }
        return rr;
    }

    /**
     * 底部文章数据
     */
    @RequestMapping("article")
    @ResponseBody
    public RestResult article(SyArticle syArticle){
        Map<Object,Object> map = new HashMap<>();
        List list = new ArrayList();
        List<String> articleTypeList = articleService.queryArticleType(syArticle);
        for (int i = 0; i <articleTypeList.size() ; i++) {
            syArticle.setArticleType(articleTypeList.get(i));
            List<Map<String, Object>> articleList = articleService.queryList(syArticle);
            list.add(articleList);
        }
        map.put("articleTypeList",articleTypeList);
        map.put("list",list);
        return new RestResult("200","查询成功",map);
    }

}
